/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: AsyncController
 * Author:   pc
 * Date:     2019/9/5 14:14
 * Description: 线程控制层
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.controller;


import com.example.rabbitmqdemo.testthread.DeferredResultHolder;
import com.example.rabbitmqdemo.testthread.MockQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 〈功能：〉<br> 
 * 〈线程控制层〉
 * @author liuhaoran
 * @create 2019/9/5 14:14
 * @since 1.0.0
 */
@Slf4j
@RestController
public class AsyncController {
	//注入模拟消息队列类
	@Autowired
	private MockQueue mockQueue;
	@Autowired
	private DeferredResultHolder deferredResultHolder;
	/**
	 * 单线程测试
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping("/order")
	public String order() throws InterruptedException {
		log.info("主线程开始");
		Thread.sleep(1000);
		log.info("主线程返回");
		return "success";
	}
	/**
	 * 用Callable实现异步
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping("/orderAsync")
	public Callable orderAsync() throws InterruptedException {
		log.info("主线程开始");
		Callable result = new Callable() {
			@Override
			public Object call() throws Exception {
				log.info("副线程开始");
				Thread.sleep(1000);
				log.info("副线程返回");
				return "success";
			}
		};
		log.info("主线程返回");
		return result;
	}
	@RequestMapping("/orderMockQueue")
	public DeferredResult orderQueue() throws InterruptedException {
		log.info("主线程开始");
		//随机生成8位数
		String orderNumber = RandomStringUtils.randomNumeric(8);
		mockQueue.setPlaceOrder(orderNumber);
		DeferredResult result = new DeferredResult();
		deferredResultHolder.getMap().put(orderNumber,result);
		Thread.sleep(1000);
		log.info("主线程返回");
		return result;
	}
	@RequestMapping("/method1")
	public synchronized void method1() {
		method2();
	}

	public synchronized void method2() {
		System.out.println("重入型锁");
	}
}